package com.score.service.impl;

import com.score.pojo.TRole;
import com.score.pojo.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TUser user = userServiceImpl.findByName(s);
        if (user != null){
            TRole role = userServiceImpl.getAuthority(user.getRoleId());
            if (role.getRole().equals("ROLE_administrators")){
                return null;
            }
            UserDetails userDetails =
                    new User(s,user.getPassword(),getAuthority(role.getRole()));
            return userDetails;
        }
        return null;
    }

    public List<SimpleGrantedAuthority> getAuthority(String authority){
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority(authority));
        return list;
    }

}
